package router

import (
	"myapp/config"
	"myapp/controllers"
	"myapp/middleware"
	"myapp/pkg"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func SetupRouter(db *gorm.DB) *gin.Engine {
	r := gin.Default()

	ossClient, err := pkg.NewOSSClient(
		config.Conf.OssEndpoint,
		config.Conf.OssAccessKeyID,
		config.Conf.OssAccessKeySecret,
		config.Conf.OssBucketName,
	)
	if err != nil {
		panic("OSS 初始化失败: " + err.Error())
	}

	path := config.Conf.UploadRoot
	r.Static("/uploads", path+"uploads")

	r.Use(middleware.SetTranslator)

	// 公共路由
	r.POST("/login", controllers.Login(db))

	r.GET("/auth-session", controllers.AuthSession(db))
	r.POST("/phone-login", controllers.LoginWechat(db))

	r.GET("/public/trend-list", controllers.TrendListHandler(db))
	r.GET("/public/trend/:id", middleware.JWTAuthMiddlewarePublic(), controllers.TrendViewHandler(db))

	r.GET("/public/recomds", middleware.JWTAuthMiddlewarePublic(), controllers.RecomdsHandler(db))
	r.GET("/public/profile/:id", middleware.JWTAuthMiddlewarePublic(), controllers.ProfileViewHandler(db))

	// 需要认证的路由组
	authGroup := r.Group("/api")
	authGroup.Use(middleware.JWTAuthMiddleware())

	authGroup.GET("/ws", pkg.WsHandler(db))

	authGroup.GET("/chat-roomid", controllers.GetRoomIdHandler(db))
	authGroup.GET("/chat-rooms", controllers.RoomListHandler(db))
	authGroup.GET("/chat-call", controllers.CallHandler(db))

	// 用户管理，只有拥有 user:create 权限的角色可以创建用户
	authGroup.POST("/users", middleware.RBACMiddleware(db, "user:create"), controllers.CreateUser(db))

	//r.GET("/test", controllers.TestHandler(db))

	// 文件上传，所有登录用户都可以
	authGroup.POST("/upload", controllers.UploadFileHandler(ossClient))

	authGroup.POST("/user-profile", controllers.ProfileHandler(db))
	authGroup.POST("/user-verify", controllers.VerifyHandler(db))
	authGroup.GET("/user-info", controllers.UserInfoHandler(db))

	authGroup.POST("/trend-post", controllers.PostHandler(db))

	// 测试接口
	authGroup.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "pong"})
	})

	return r
}
